package com.yyx.server.service.impl;

import com.yyx.server.pojo.Admin;
import com.yyx.server.pojo.Menu;
import com.yyx.server.mapper.MenuMapper;
import com.yyx.server.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author YongXin
 * @since 2021-07-24
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    /**
     * 根据用户ID查询菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenusByAdminId() {
        Integer id = ((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        //从redis中获取menus
        List<Menu> menus = (List<Menu>) opsForValue.get("menu_" + id);
        //redis中不存在
        if (CollectionUtils.isEmpty(menus)){
            //从数据库中获取
            menus = menuMapper.getMenusByAdminId(id);
            //存入redis
            opsForValue.set("menu_"+id,menus);
        }
        return menus;
    }
    /**
     * 根据角色获取菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenusWithRole() {
        return menuMapper.getMenusWithRole();
    }

    @Override
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }
}
